import fs from 'node:fs';
import path from 'node:path';

// 检测并创建 config 文件夹
const configDir = './plugins/person-plugin/config';
const defSetDir = './plugins/person-plugin/defSet';
const plugin = './plugins/person-plugin';
// 如果没有 config 文件夹，则创建
if (!fs.existsSync(configDir)) {
  fs.mkdirSync(configDir, { recursive: true });
  logger.info(logger.green(`创建了文件夹：${configDir}`));
}

// 复制 config.yaml 和 help.yaml 文件到 config 文件夹
const filesToCopy = ['config.yaml', 'help.yaml'];
filesToCopy.forEach((file) => {
  const src = path.join(defSetDir, file);
  const dest = path.join(configDir, file);

  if (fs.existsSync(src)) {
    fs.copyFileSync(src, dest);
    logger.info(logger.green(`复制了文件：${file} 到 ${configDir}`));
  } else {
    logger.error(logger.red(`文件不存在：${src}`));
  }
});

// 定义全局帮助版本函数
async function globalVersion() {
  let PluginVersion = JSON.parse(fs.readFileSync(`${plugin}/package.json`, 'utf-8'));
  PluginVersion = PluginVersion.version;
  global.PluginVersion = PluginVersion;
}

// 调用全局帮助版本函数
await globalVersion();

if (!global.segment) {
  global.segment = (await import("icqq")).segment;
}

const files = fs
  .readdirSync('./plugins/person-plugin/apps')
  .filter((file) => file.endsWith('.js'));

let ret = [];

files.forEach((file) => {
  ret.push(import(`./apps/${file}`));
});

ret = await Promise.allSettled(ret);

let apps = {};
for (let i in files) {
  let name = files[i].replace('.js', '');

  if (ret[i].status != 'fulfilled') {
    logger.error(`载入插件错误：${logger.red(name)}`);
    logger.error(ret[i].reason);
    continue;
  }
  apps[name] = ret[i].value[Object.keys(ret[i].value)[0]];
}

export { apps };

logger.info(logger.yellow('----------人机插件----------'));
logger.info(logger.yellow('                           '));
logger.info(logger.yellow('       SSSSS   BBBBB       '));
logger.info(logger.yellow('      S        B    B      '));
logger.info(logger.yellow('       SSSSS   BBBBB       '));
logger.info(logger.yellow('           S   B    B      '));
logger.info(logger.yellow('       SSSSS   BBBBB       '));
logger.info(logger.yellow('                           '));
logger.info(logger.yellow('----欢迎加入Q群：983299064----'));
